import useSafeStore from "@/store/modules/safe";
// 指纹校验
export const Authentication = async () => {
  let authentication = false;
  try {
    authentication = await startSoterAuthenticationFingerPrint();
  } catch (e) {
    // console.log("e",e);
  }
  return authentication;
};

// 检查是否支持指纹识别
export const IsSupportSoter = async () => {
  let isSupport = false;
  try {
    await checkIsSupportSoterAuthentication();
    await checkIsSoterEnrolledInDeviceFingerPrint();
    isSupport = true;
  } catch (e) {
    // console.log("e",e);
  }
  return isSupport;
};

// 检查是否支持指纹识别
const checkIsSupportSoterAuthentication = () => {
  return new Promise((resolve, reject) => {
    uni.checkIsSupportSoterAuthentication({
      success(res) {
        if (res.supportMode.indexOf("fingerPrint") !== -1) {
          resolve(true);
        } else {
          reject("不支持指纹识别");
        }
      },
      fail(err) {
        reject("检查支持指纹识别失败");
      },
    });
  });
};

//检测是否录入指纹
const checkIsSoterEnrolledInDeviceFingerPrint = () => {
  return new Promise((resolve, reject) => {
    uni.checkIsSoterEnrolledInDevice({
      checkAuthMode: "fingerPrint",
      success(res) {
        if (res.isEnrolled) {
          resolve(true);
        } else {
          reject("没有录入指纹");
        }
      },
      fail(err) {
        reject("检测是否录入指纹失败");
      },
    });
  });
};

//校验指纹
const startSoterAuthenticationFingerPrint = () => {
  return new Promise((resolve, reject) => {
    uni.startSoterAuthentication({
      requestAuthModes: ["fingerPrint"],
      challenge: "assen",
      authContent: "请用指纹解锁",
      success(res) {
        resolve(true);
      },
      fail(err) {
        reject("指纹验证失败");
      },
    });
  });
};

// 判断校验是否通过
export const isAuthPass = () => {
  const safeStore = useSafeStore();
  if (safeStore.fingerPrint || safeStore.usePassword) {
    if (!safeStore.isAuth) {
      uni.showToast({
        title: "身份验证失败，无法操作",
        icon: "none",
        duration: 2000,
      });
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
};
